package GUI;

import util.User;
import util.UserDAO;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 注册界面
 */
public class RegisterFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;
    private JTextField nameField;
    private JTextField contactField;
    private JTextField regionField;
    private JButton registerButton;
    private JButton backButton;
    private JLabel messageLabel;

    private LoginFrame loginFrame;

    public RegisterFrame(LoginFrame loginFrame) {
        this.loginFrame = loginFrame;

        // 设置窗口标题和大小
        setTitle("绿色出行系统 - 注册");
        setSize(500, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示
        setResizable(false);

        // 设置自定义内容面板（带渐变背景）
        setContentPane(new GradientPanel());
        getContentPane().setLayout(new BorderLayout());

        // 创建标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);
        titlePanel.setBorder(new EmptyBorder(20, 0, 10, 0));

        JLabel titleLabel = new JLabel("用户注册", JLabel.CENTER);
        titleLabel.setFont(new Font("等线", Font.BOLD, 24));
        titleLabel.setForeground(new Color(0, 100, 0));
        titlePanel.add(titleLabel, BorderLayout.CENTER);

        getContentPane().add(titlePanel, BorderLayout.NORTH);

        // 创建注册面板
        JPanel registerPanel = new JPanel();
        registerPanel.setLayout(new GridBagLayout());
        registerPanel.setOpaque(false);
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(10, 15, 10, 15);

        // 创建用户名标签和文本框
        addFormField(registerPanel, constraints, "用户名:", usernameField = new RoundedTextField(20), 0);

        // 创建密码标签和密码框
        addFormField(registerPanel, constraints, "密码:", passwordField = new RoundedPasswordField(20), 1);

        // 创建确认密码标签和密码框
        addFormField(registerPanel, constraints, "确认密码:", confirmPasswordField = new RoundedPasswordField(20), 2);

        // 创建姓名标签和文本框
        addFormField(registerPanel, constraints, "姓名:", nameField = new RoundedTextField(20), 3);

        // 创建联系方式标签和文本框
        addFormField(registerPanel, constraints, "联系方式:", contactField = new RoundedTextField(20), 4);

        // 创建所在地区标签和文本框
        addFormField(registerPanel, constraints, "所在地区:", regionField = new RoundedTextField(20), 5);

        // 创建密码规则提示
        JLabel passwordRuleLabel = new JLabel("<html><small>密码要求：包含字母和数字，长度至少8位</small></html>");
        passwordRuleLabel.setFont(new Font("等线", Font.ITALIC, 12));
        passwordRuleLabel.setForeground(new Color(100, 100, 100));
        constraints.gridx = 1;
        constraints.gridy = 6;
        constraints.anchor = GridBagConstraints.WEST;
        registerPanel.add(passwordRuleLabel, constraints);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);

        // 创建注册按钮
        registerButton = new RoundedButton("注册");
        registerButton.setFont(new Font("等线", Font.BOLD, 14));
        registerButton.setPreferredSize(new Dimension(120, 40));
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                register();
            }
        });
        buttonPanel.add(registerButton);

        // 创建返回按钮
        backButton = new RoundedButton("返回登录");
        backButton.setFont(new Font("等线", Font.BOLD, 14));
        backButton.setPreferredSize(new Dimension(120, 40));
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                backToLogin();
            }
        });
        buttonPanel.add(backButton);

        constraints.gridx = 0;
        constraints.gridy = 7;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.CENTER;
        registerPanel.add(buttonPanel, constraints);

        // 创建消息标签
        messageLabel = new JLabel("", JLabel.CENTER);
        messageLabel.setFont(new Font("等线", Font.PLAIN, 12));
        messageLabel.setForeground(Color.RED);
        constraints.gridx = 0;
        constraints.gridy = 8;
        constraints.gridwidth = 2;
        registerPanel.add(messageLabel, constraints);

        // 添加注册面板到内容面板
        JScrollPane scrollPane = new JScrollPane(registerPanel);
        scrollPane.setBorder(null);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 添加底部版权信息
        JLabel copyrightLabel = new JLabel("© 2025 绿色出行系统 版权所有", JLabel.CENTER);
        copyrightLabel.setFont(new Font("等线", Font.PLAIN, 10));
        copyrightLabel.setForeground(new Color(100, 100, 100));
        copyrightLabel.setBorder(new EmptyBorder(10, 0, 10, 0));
        getContentPane().add(copyrightLabel, BorderLayout.SOUTH);
    }

    /**
     * 添加表单字段
     */
    private void addFormField(JPanel panel, GridBagConstraints constraints, String labelText, JComponent field,
            int row) {
        JLabel label = new JLabel(labelText);
        label.setFont(new Font("等线", Font.BOLD, 14));
        label.setForeground(new Color(50, 50, 50));
        constraints.gridx = 0;
        constraints.gridy = row;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel.add(label, constraints);

        if (field instanceof JTextField) {
            ((JTextField) field).setFont(new Font("等线", Font.PLAIN, 14));
        }
        constraints.gridx = 1;
        constraints.gridy = row;
        constraints.anchor = GridBagConstraints.WEST;
        panel.add(field, constraints);
    }

    /**
     * 处理注册逻辑
     */
    private void register() {
        String username = usernameField.getText();
        String password = new String(passwordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());
        String name = nameField.getText();
        String contact = contactField.getText();
        String region = regionField.getText();

        // 检查输入是否完整
        if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty() ||
                name.isEmpty() || contact.isEmpty() || region.isEmpty()) {
            showErrorMessage("所有字段都必须填写！");
            return;
        }

        // 检查用户名格式
        if (username.length() < 4) {
            showErrorMessage("用户名长度至少为4个字符！");
            return;
        }

        // 检查密码强度
        if (password.length() < 8 || !password.matches(".*[a-zA-Z].*") || !password.matches(".*[0-9].*")) {
            showErrorMessage("密码必须至少包含8个字符，且包含字母和数字！");
            return;
        }

        // 检查两次输入的密码是否一致
        if (!password.equals(confirmPassword)) {
            showErrorMessage("两次输入的密码不一致！");
            return;
        }

        // 创建用户对象并尝试注册
        User user = new User(username, password, name, contact, region);
        UserDAO userDAO = new UserDAO();

        boolean success = userDAO.registerUser(user);

        if (success) {
            JOptionPane.showMessageDialog(this,
                    "注册成功！请返回登录页面登录。",
                    "注册成功",
                    JOptionPane.INFORMATION_MESSAGE);
            backToLogin();
        } else {
            showErrorMessage("注册失败，用户名可能已存在！");
        }
    }

    /**
     * 显示错误信息
     */
    private void showErrorMessage(String message) {
        messageLabel.setText(message);
        // 使用计时器让消息在5秒后消失
        Timer timer = new Timer(5000, e -> messageLabel.setText(""));
        timer.setRepeats(false);
        timer.start();
    }

    /**
     * 返回登录界面
     */
    private void backToLogin() {
        loginFrame.setVisible(true);
        dispose();
    }

    /**
     * 渐变背景面板
     */
    private class GradientPanel extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            int w = getWidth();
            int h = getHeight();

            // 创建渐变颜色
            GradientPaint gradient = new GradientPaint(0, 0, new Color(230, 250, 230),
                    0, h, new Color(200, 230, 200));
            g2d.setPaint(gradient);
            g2d.fillRect(0, 0, w, h);

            // 添加一些装饰性元素
            g2d.setColor(new Color(0, 100, 0, 20));
            for (int i = 0; i < 5; i++) {
                int size = 50 + i * 20;
                g2d.fillOval(w - size - 20, h - size - 20, size, size);
            }

            // 左上角装饰
            g2d.setColor(new Color(0, 100, 0, 15));
            for (int i = 0; i < 3; i++) {
                int size = 30 + i * 15;
                g2d.fillOval(20, 20, size, size);
            }
        }
    }

    /**
     * 圆角文本框
     */
    private class RoundedTextField extends JTextField {
        public RoundedTextField(int columns) {
            super(columns);
            setOpaque(false);
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(180, 180, 180)),
                    BorderFactory.createEmptyBorder(5, 10, 5, 10)));
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(new Color(255, 255, 255, 220));
            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);
            super.paintComponent(g);
            g2.dispose();
        }
    }

    /**
     * 圆角密码框
     */
    private class RoundedPasswordField extends JPasswordField {
        public RoundedPasswordField(int columns) {
            super(columns);
            setOpaque(false);
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(180, 180, 180)),
                    BorderFactory.createEmptyBorder(5, 10, 5, 10)));
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(new Color(255, 255, 255, 220));
            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);
            super.paintComponent(g);
            g2.dispose();
        }
    }

    /**
     * 圆角按钮
     */
    private class RoundedButton extends JButton {
        public RoundedButton(String text) {
            super(text);
            setOpaque(false);
            setFocusPainted(false);
            setBorderPainted(false);
            setContentAreaFilled(false);
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            if (getModel().isPressed()) {
                g2.setColor(new Color(0, 100, 0));
            } else if (getModel().isRollover()) {
                g2.setColor(new Color(0, 130, 0));
            } else {
                g2.setColor(new Color(0, 150, 0));
            }

            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);

            g2.setColor(Color.WHITE);
            g2.setFont(getFont());
            FontMetrics fm = g2.getFontMetrics();
            int x = (getWidth() - fm.stringWidth(getText())) / 2;
            int y = (getHeight() - fm.getHeight()) / 2 + fm.getAscent();
            g2.drawString(getText(), x, y);
            g2.dispose();
        }
    }
}
